<template>
    <a-layout>
        <a-layout-sider :style="pageLayoutSiderStyle">
            <div class="sider-inner" :style="{width:showSide?'100%':'10px'}">
                <div class="switch" @click="switchSider">
                    <a-icon type="backward" v-if="showSide" />
                    <a-icon type="forward" v-else />
                </div>
                <div class="list" v-if="showSide">
                    <a-tree
                        v-if="treeData.length>0"
                        :key="treeDataKey"
                        :defaultExpandedKeys="expandedKeys"
                        :auto-expand-parent="autoExpandParent"
                        :selected-keys="selectedKeys"
                        :tree-data="treeData" 
                        @expand="onExpand"
                        @select="onSelect"
                    >
                        <template slot="title" slot-scope="item">
                            <div class="tree-name-wrap" v-if="item.type==='new'" @click.stop>
                                <a-input v-model="newName" size="small" @click.stop style="width:80px" />
                                <a-icon type="check-circle" theme="filled" @click.stop="saveNewFolder(item)" />
                                <a-icon type="close-circle" theme="filled" @click.stop="cancelNewFolder" />
                            </div>
                            <div class="tree-name-wrap" v-else>
                                <div v-if="item.editStatus===0">
                                    {{item.titleCopy}}
                                    <a-icon type="plus-circle" @click.stop="addNode(item)" />
                                    <a-icon type="edit" @click.stop="editNode(item)" />
                                    <a-icon type="delete" @click.stop="deleteNode(item)"  v-if="item.parentId!==-1" />
                                </div>
                                <div v-else>
                                    <a-input v-model="newName" size="small" @click.stop style="width:80px" />
                                    <a-icon type="check-circle" theme="filled" @click.stop="saveEditFolder(item)" />
                                    <a-icon type="close-circle" theme="filled" @click.stop="cancelNewFolder" />
                                </div>
                            </div>
                        </template>
                    </a-tree>
                    <div v-else>
                        <a-button type="primary" size="small" class="add-article" @click="addRootFolder=true" v-if="!addRootFolder">
                            <span class="iconfont icon-piliangtianjia"></span>添加根目录
                        </a-button>
                        <div class="tree-name-wrap" v-else>
                            <a-input v-model="newName" size="small" @click.stop style="width:80px" />
                            <a-icon type="check-circle" theme="filled" @click.stop="saveNewFolder()" />
                            <a-icon type="close-circle" theme="filled" @click.stop="addRootFolder=false;newName=''" />
                        </div>
                    </div>
                </div>
            </div>
        </a-layout-sider>
        <a-layout-content>
            <a-tabs default-active-key="1">
                <template slot="tabBarExtraContent">
                    <a-input-search placeholder="请输入查询内容" v-model="keyword" style="width: 200px" @search="onSearch" />
                    <a-button type="primary" size="small" class="add-article" @click="editVisible=true">
                        <span class="iconfont icon-piliangtianjia"></span>新增原文
                    </a-button>
                    <a-button type="primary" size="small" class="del-article" @click="multiDelete">
                        <span class="iconfont icon-shanchu"></span>删除原文
                    </a-button>
                </template>
                <a-tab-pane key="1" tab="原文查看"></a-tab-pane>
            </a-tabs>
            <div class="table-wrap">
                <a-table :data-source="articles" :rowKey="record=>record.fileId" :pagination="pageSetting" @change="changeTable" :row-selection="rowSelection">
                    <a-table-column key="fileId" title="序号" data-index="fileId" :width="60" />
                    <a-table-column key="fileName" title="标题" data-index="fileName" :width="250" />
                    <a-table-column key="fileDesc" title="文件描述" data-index="fileDesc">
                        <template slot-scope="text">
                            <div v-html="text"></div>
                        </template>
                    </a-table-column>
                    <a-table-column key="realName" title="上传者" data-index="realName" :width="100" />
                    <a-table-column key="createTime" title="上传时间" data-index="createTime" :width="180" />
                    <a-table-column title="操作" data-index="action" :width="180" align="center">
                        <template slot-scope="text,record">
                            <a-button type="link" @click="edit(record)">编辑</a-button>
                            <a-button type="link" @click="deleteArticle(record.fileId)">删除</a-button>
                        </template>
                    </a-table-column>
                </a-table>
            </div>

            <a-modal 
                :title="waitingEdit?'编辑原文':'新增原文'"
                :visible="editVisible"
                centered
                :footer="null"
                :width="970"
                wrapClassName="edit-cube-win"
                @cancel="cancelEdit">

                <div class="inputs">
                    <a-row :gutter="[16,16]">
                        <a-col :span="24">
                            <a-row type="flex">
                                <a-col flex="100px" class="label">文件名称</a-col>
                                <a-col flex="auto">
                                    <a-input v-model="fileName" />
                                </a-col>
                            </a-row>
                        </a-col>
                    </a-row>                    

                    <a-row :gutter="[16,16]">
                        <a-col :span="24">
                            <a-row type="flex">
                                <a-col flex="100px" class="label">文件描述</a-col>
                                <a-col flex="auto">
                                    <quill-editor :options="editorOption" :content="fileDesc" @change="onEditorChange" style="height:150px" />
                                </a-col>
                            </a-row>
                        </a-col>
                    </a-row>

                    <div style="height:60px;"></div>   

                    <a-row :gutter="[16,16]">
                        <a-col :span="24">
                            <a-row type="flex">
                                <a-col flex="100px" class="label">文件上传</a-col>
                                <a-col flex="auto">
                                    <a-input style="width:300px" :disabled="true" :value="fileUrl" />
                                    <a-upload
                                        :show-upload-list="false" 
                                        @change="handlePreview" 
                                        :before-upload="handleChangeFile" 
                                        accept=".pdf"
                                    >
                                        <a-button type="primary"  class="upload-btn">选择文件</a-button>
                                    </a-upload>
                                </a-col>
                            </a-row>
                        </a-col>
                    </a-row>                 
                </div>

                <div class="btns">
                    <a-button @click="cancelEdit">取消</a-button>
                    <a-button type="primary" @click="confirmEdit" :disabled="uploading">确定</a-button>
                </div>
            </a-modal>
        </a-layout-content>
    </a-layout>
</template>

<script>
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import {pageLayoutSiderStyle,pageLayoutSiderHideStyle} from '../../until/global_style';
import { messageTips,getCookie } from '../../until/tools';
import config from '../../until/configs';
import reqwest from 'reqwest';
import { quillEditor } from 'vue-quill-editor';
export default {
    name:'Articles',
    components:{quillEditor},
    data() {
        return {
            pageLayoutSiderStyle:pageLayoutSiderStyle,
            showSide:true,
            autoExpandParent: true,
            newName:'',
            addRootFolder:false,
            treeDataKey:0,
            selectedKeys: [],
            expandedKeys: [],
            treeData:[],
            selectedRowKeys:[],
            articles:[],
            keyword:'',
            page:{},
            rowSelection:{
                onChange: (selectedRowKeys) => {
                    this.selectedRowKeys = selectedRowKeys;
                },
                onSelect: (record, selected, selectedRows) => {
                    this.selectedRowKeys = selectedRows.map(item=>item.fileId);
                },
                onSelectAll: (selected, selectedRows) => {
                    this.selectedRowKeys = selectedRows.map(item=>item.fileId)
                },
            },
            uploadUrl:config.inputs_upload_dim_data+'?sid='+getCookie('bd_sid'),
            editorOption: {
                placeholder: "请在这里输入",
                height:200,
                theme:'snow',
                modules:{
                    toolbar:[
                        ['bold', 'italic'],    //加粗，斜体，下划线，删除线
                        ['blockquote'],     //引用，代码块
                        [{ 'header': 1 }, { 'header': 2 }],        // 标题，键值对的形式；1、2表示字体大小
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],     //列表
                        [{ 'indent': '-1'}, { 'indent': '+1' }],     // 缩进
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],     //几级标题
                        [{ 'align': [] }],    //对齐方式
                        //['image']    //上传图片、上传视频
                    ]
                }
            },
            fileName:'',
            fileDesc:'',
            waitingEdit:null,
            editVisible:false,
            fileUrl:null,
            waitingUploadFile:null,
            uploading:false,
        }
    },
    computed:{
        folderId() {
            let id = this.$route.query.folderId;
            if(id) {
                return parseInt(id);
            }
            return null;
        },
        pageSetting(){
			let pageSize=0;
			if(this.page.allSize) {
				pageSize = this.page.allSize;
			}
			return {
				showQuickJumper:true,
				hideOnSinglePage:true,
				showTotal:()=>`共${pageSize}条`,
				total:pageSize,
			}
		},
    },
    watch:{
        folderId(value) {
            if(value) {
                this.getArticles();
            }
        }
    },
    created() {
        this.getFolders().then(res=>{
            if(!this.folderId) {                
                if(res&&this.treeData[0]) {
                    this.selectedKeys = [this.treeData[0].folderId];
                    this.$router.push({path:'inputs_article',query:{folderId:this.treeData[0].folderId}});
                }                
            } else {
                this.selectedKeys = [this.folderId];
            }
        });
        if(this.folderId) {
            this.getArticles();
        }
    },
    methods:{
        switchSider() {
            this.showSide = !this.showSide;
            if(this.showSide) {
                this.pageLayoutSiderStyle = pageLayoutSiderStyle;
            } else {
                this.pageLayoutSiderStyle = pageLayoutSiderHideStyle
            }
        },

        getFolders() {
            return this.$http.inputs_get_article_folder().then(res=>{
                if(res) {
                    if(res.list) {
                        res.list.forEach(item=>{   
                            item.title = item.folderName;         
                            item.scopedSlots = { title: 'title' };
                            item.titleCopy = item.title;
                            item.key = item.folderId;
                            item.editStatus = 0;
                        });
                        this.treeData = this.setTree(res.list,-1,[]);
                    }
                }
                return true;
            });
        },

        setTree(arr,pid,result) {
            arr.forEach(item=>{
                if(item.parentId===pid) {
                    item.children = this.setTree(arr,item.folderId,[]);
                    result.push(item);
                }
            })
            return result;
        },

        onExpand(e) {
            this.expandedKeys = e;
        },

        onSelect(selectedKeys) {
            this.selectedKeys = selectedKeys;
            this.$router.push({path:'inputs_article',query:{folderId:selectedKeys[0]}});
        },

        onSearch(e) {
            let params = {currentPage:1}
            if(e) {
                params.dimFileName = e;
            }
            this.getArticles(params);
        },
        changeTable(e) {
            let params = {currentPage:e.current}
            if(this.keyword) {
                params.dimFileName = this.keyword;
            }
            this.getArticles(params);
        },
        getArticles(obj) {
            let params = {folderId:this.folderId};
            if(obj) {
                params={...params,...obj}
            }
            this.$http.inputs_get_articles(params).then(res=>{
                if(res) {
                    if(res.list) {
                        this.articles = res.list;
                        this.page = res.page;
                    }
                }
            })
        },
        addNode(e) {
            this.newName = '';
            let hasNewForm ;
            e.dataRef.children.some((item,key)=>{
                if(item.type==='new') {
                    hasNewForm = key;
                }
            });
            if(hasNewForm) {
                e.dataRef.children.splice(hasNewForm,1);
            }
            this.expandedKeys.push(e.eventKey);
            e.dataRef.children.unshift({ title: '', key: `${e.eventKey}-0`,type:'new',pid:e.eventKey });
            this.treeDataKey = Math.random();
            this.treeData = [...this.treeData];
        },
        editNode(e) {
            this.newName = e.dataRef.title;
            e.dataRef.editStatus = 1;
            this.treeDataKey = Math.random();
            this.treeData = [...this.treeData];
        },
        saveNewFolder(e) {
            let params;
            if(e) {
                params = {
                    folderName:this.newName,
                    ord:1,
                    parentId:e.dataRef.pid
                }
            } else {
                params = {
                    folderName:this.newName,
                    ord:1,
                    parentId:-1
                }
            }
            this.$http.inputs_create_article_folder(params).then(res=>{
                if(res) {
                    if(res.success) {
                        this.getFolders();
                    } else {
                        messageTips(res.message,2);
                    }
                }
            })
        },
        saveEditFolder(e) {
            let params = {
                folderName:this.newName,
                ord:1,
                folderId:e.dataRef.folderId,
                parentId:e.dataRef.parentId
            }
            this.$http.inputs_update_article_folder(params).then(res=>{
                if(res) {
                    if(res.success) {
                        this.getFolders();
                    } else {
                        messageTips(res.message,2);
                    }
                }
            })
        },
        cancelNewFolder() {   
            this.getFolders();
        },
        deleteNode(e) {
            let that = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除吗？',
                okText: '确定',
                cancelText: '取消',
                centered:true,
                onOk() {
                    that.$http.inputs_delete_article_folder({folderId:e.dataRef.folderId}).then(res=>{
                        if(res) {
                            if(res.success) {
                                messageTips(res.message,3);
                                that.getFolders();
                            }else {
                                messageTips(res.message,1);
                            }
                        }
                    });
                }
            });
        },
        cancelEdit() {
            this.editVisible = false;
            this.fileName = '';
            this.fileDesc = '';
            this.waitingEdit = null;
            this.editVisible = false;
            this.fileUrl = null;
            this.waitingUploadFile = null;
        },
        edit(item) {
            this.$http.inputs_get_article_detail({fileId:item.fileId}).then(res=>{
                if(res) {
                    if(res.dimFile) {
                        this.editVisible = true;
                        this.waitingEdit = item.fileId;
                        this.fileName = item.fileName;
                        this.fileDesc = item.fileDesc;
                        this.fileUrl = res.dimFile.showName;
                    }
                }
            })
        },
        confirmEdit() {
            if(!this.folderId) {
                messageTips('请选择左侧目录',2);
                return false;
            }
            const formData = new FormData();
            let funName;
            if(this.fileName==='') {
                messageTips('请填写文件名称',2);
                return false;
            }
            if(!this.waitingEdit) {
                if(!this.waitingUploadFile) {
                    messageTips('请上传文件',2);
                    return false;
                }
                funName = config.addDimFile+'?sid='+getCookie('bd_sid');
                formData.append('file', this.waitingUploadFile);
                formData.append('folderId', this.folderId);
                formData.append('fileName', this.fileName);
                formData.append('fileDesc', this.fileDesc);
            } else {
                funName = config.updateDimFile+'?sid='+getCookie('bd_sid');                
                formData.append('fileId', this.waitingEdit);
                formData.append('file', this.waitingUploadFile);
                formData.append('folderId', this.folderId);
                formData.append('fileName', this.fileName);
                formData.append('fileDesc', this.fileDesc);
            }
            this.uploading = true;
            reqwest({
                url: funName,
                method: 'post',
                processData: false,
                data: formData,
                contentType : false,
                success: (res) => {
                    this.uploading = false;
                    if(res) {
                        if(res.success) {
                            if(this.waitingEdit) {
                                let params = {currentPage:this.page.currentPage}
                                if(this.keyword) {
                                    params.dimFileName = this.keyword;
                                }
                                this.getArticles(params);
                            } else {
                                this.getArticles();
                            }
                            messageTips(res.message,3);
                            this.editVisible = false;
                            this.fileName = '';
                            this.fileDesc = '';
                            this.fileUrl = null;
                            this.waitingUploadFile = null;
                            this.waitingEdit = null;
                        } else {
                            messageTips(res.message,1);
                        }                        
                    }
                },
                error: () => {
                
                },
            });
        },
        onEditorChange(e) {
            this.fileDesc = e.html;
        },
        handlePreview({file}) {
            this.fileUrl = file.name;
        },
        handleChangeFile(info) {
            this.waitingUploadFile = info;
        },
        
        deleteArticle(fileIds) {
            var that = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除吗？',
                okText: '确定',
                cancelText: '取消',
                centered:true,
                onOk() {
                    that.$http.inputs_delete_articles({fileIds}).then(res=>{
                        if(res) {
                            if(res.success) {
                                messageTips(res.message,3);
                                let params = {currentPage:that.page.currentPage}
                                if(that.keyword) {
                                    params.dimFileName = that.keyword;
                                }
                                that.getArticles(params);
                            } else {
                                messageTips(res.message,1);
                            }
                        }
                    })
                }
            });
        },
        multiDelete() {
            if(this.selectedRowKeys.length===0) {
                messageTips('请选择要删除的数据',2);
                return false;
            }
            this.deleteArticle(this.selectedRowKeys.join(','));
        }
    }
}
</script>

<style lang="scss">
    @import '../../scss/articles.scss';
</style>